package ar.edu.itba.it.pdc.nio;

import java.nio.channels.SelectionKey;

import ar.edu.itba.it.pdc.httpParser.models.HttpRequest;
import ar.edu.itba.it.pdc.monitoring.MonitoringProtocol;
import ar.edu.itba.it.pdc.monitoring.ProxyMonitoring;




public class Connection {

	private SelectionKey requestKey;
	
	private UnidirectionalConnection request;
	private UnidirectionalConnection response;

	private boolean entablished = false;
	
	public Connection(SelectionKey requestKey) {
		
		request = new UnidirectionalConnection(ConectionType.REQUEST, requestKey);
		this.requestKey=requestKey;
	}
	
	public void setResponseKey(SelectionKey responseKey){
		request.setWkey(responseKey);
		response = new UnidirectionalConnection(ConectionType.RESPONSE, responseKey);
		response.setHttpRequest((HttpRequest) request.getModel());
		response.setWkey(requestKey);
		
		ProxyMonitoring.getInstance().openConnection();
		entablished = true;
	}
	
	public boolean isEntablished(){
		return entablished;
	}

	public UnidirectionalConnection getRequest() {
		return request;
	}

	public UnidirectionalConnection getResponse() {
		return response;
	}
	
	public enum ConectionType{REQUEST,RESPONSE}

	public void setEntablished(boolean b) {
		entablished = b;		
	}

	public void returnError(String errorCode, String errorMessage) throws MemoryAllocationLimitHited {
		response = new UnidirectionalConnection();
		response.setWkey(requestKey);
		response.generateError(errorCode, errorMessage);
		
		request.close();
		
		response.close();
		
		entablished = true;
	}

	public void retriveBuffers() {
		request.retriveBuffers();
		if(response != null){
			response.retriveBuffers();
		}
	}


}
